package com.boarsoft.boar.code.svc.biz.impl;

import java.util.List;
import java.util.Objects;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.boarsoft.boar.code.entity.BeanInfo;
import com.boarsoft.boar.code.entity.MethodParamInfo;
import com.boarsoft.boar.code.svc.biz.MethodParamInfoBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("methodParamInfoBiz")
public class MethodParamInfoBizImpl extends SimpleBizImpl implements MethodParamInfoBiz {
	/**
	 * 保存method的参数信息
	 * 
	 * @param methodParamInfo 方法参数信息
	 * @return id
	 */
	@Transactional
	@Override
	public String save(MethodParamInfo methodParamInfo) {
		String id = this.seleteByMethodIdAndName(methodParamInfo.getMethodId(), methodParamInfo.getName());
		if (Util.strIsEmpty(id)) {
			return (String) this.dao.save(methodParamInfo);
		} else {
			this.update(id, methodParamInfo.getType());
			return id;
		}
	}

	@Transactional(readOnly = true)
	public String seleteByMethodIdAndName(String methodId, String name) {
		Query<MethodParamInfo> qry = this.dao.createQuery(MethodParamInfo.class,
				"from MethodParamInfo where methodId = :methodId and name = :name ");
		qry.setParameter("methodId", methodId);
		qry.setParameter("name", name);
		MethodParamInfo methodParamInfos = qry.uniqueResult();
		if (Objects.nonNull(methodParamInfos) && Objects.nonNull(methodParamInfos.getId())) {
			return methodParamInfos.getId();
		}
		return null;
	}

	@Transactional(readOnly = true)
	@Override
	public PagedResult<BeanInfo> list(String methodId, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from MethodParamInfo r where 1=1");
		if (Util.strIsNotEmpty(methodId)) {
			sb.append(" and r.methodId = '").append(methodId).append("'");
		}
		sb.append(" order by r.id");
		List<BeanInfo> lt = this.dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<BeanInfo>(lt.size(), lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public void deleteByMethodId(String methodId) {
		Query<MethodParamInfo> qry = this.dao.createQuery(MethodParamInfo.class, "from MethodParamInfo where methodId = :methodId ");
		qry.setParameter("methodId", methodId);

		List<MethodParamInfo> methodParamInfos = qry.list();
		if(!CollectionUtils.isEmpty(methodParamInfos)) {
			for (MethodParamInfo methodParamInfo : methodParamInfos) {
				this.dao.delete(methodParamInfo);
			}
		}
	}

	@Transactional
	public void update(String id, String type) {
		String hql = " update MethodParamInfo set type = '" + type +
				"' where id = '" + id + "'";
		this.dao.executeUpdate(hql);
	}
}
